package com.example.github.jdbc;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.example.github.jdbc.entity.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class BrandDML {
    public static void main(String[] args) throws Exception {
        // 1. 初始化配置类
        Properties properties = new Properties();
        // 2. 加载druid 配置文件
        properties.load(new FileInputStream("postman/src/main/resources/druid.properties"));
        // 3. druid 工厂加载配置信息
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        // 4. 创建连接
        Connection connection = dataSource.getConnection();
        // 5. 执行sql
        String sql = "select * from tb_brand";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Brand> brands = queryBrands(resultSet);
        System.out.println(brands);
    }

    /**
     * 查询所有品牌信息
     *
     * @param resultSet 数据库中查询出来的结果集
     * @return list
     * @throws SQLException SQLException
     */
    private static List<Brand> queryBrands(ResultSet resultSet) throws SQLException {
        List<Brand> brands = new ArrayList<>();
        // 循环遍历获取值
        while (resultSet.next()) {
            Brand brand = new Brand();
            int id = resultSet.getInt("id");
            String brandName = resultSet.getString("brand_name");
            String companyName = resultSet.getString("company_name");
            String description = resultSet.getString("description");
            int ordered = resultSet.getInt("ordered");
            int status = resultSet.getInt("status");

            brand.setId(id);
            brand.setBrandName(brandName);
            brand.setDescription(description);
            brand.setOrdered(ordered);
            brand.setStatus(status);
            brand.setCompanyName(companyName);

            brands.add(brand);
        }
        return brands;
    }
}
